"""
数据分析
"""

from typing import List, Dict, Optional, Tuple
import json
import requests
from db_utils import CommentAnalysisDB, UserReviewDB

class OllamaCommentAnalyzer:
    def __init__(self,
                 ollama_url: str = 'http://localhost:11434/api/chat',
                 model_name: str = 'qwen3:30b-a3b'):
        """
        初始化评论分析工具

        :param ollama_url: Ollama API地址 (默认: http://localhost:11434/api/generate)
        :param model_name: 使用的模型名称 (默认: llama3)
        """
        self.ollama_url = ollama_url
        self.model_name = model_name

    def analyze_comment(self, comment_text: str) -> Dict[str, List[str]]:
        """
        分析单条评论的优缺点

        :param comment_text: 需要分析的评论内容
        :return: 包含优点和缺点的字典，格式:
                {
                    "advantages": ["优点1", "优点2"],
                    "disadvantages": ["缺点1", "缺点2"],
                    "model": "模型名称"
                }
        """
        # 调用API
        api_response = self._call_ollama(comment_text)

        # 解析结果

        advantages, disadvantages = self._parse_analysis_result(json.loads(api_response))

        return {
            "advantages": advantages,
            "disadvantages": disadvantages,
        }

    def batch_analyze(self, comments: List[str]) -> List[Dict[str, List[str]]]:
        """
        批量分析多条评论

        :param comments: 评论内容列表
        :return: 分析结果列表，每个元素格式同analyze_comment返回值
        """
        results = []
        for comment in comments:
            try:
                result = self.analyze_comment(comment)
                results.append(result)
            except Exception as e:
                print(f"分析评论失败: {str(e)}")
                results.append({
                    "advantages": [],
                    "disadvantages": [],
                    "model": self.model_name,
                    "error": str(e)
                })
        return results

    def _call_ollama(self, query: str) -> str:
        payload = {
            "model": "qwen3:30b-a3b",
            "messages": [
                {
                    "role": "system",
                    "content": "你是一个汽车评论分析专家，请以专业的角度抽取出用户评论中优点和缺点。要求：1. 语言简洁 2. 返回结果一定是json格式，返回前校验格式是否正确，如果不正确进行修正，json格式{\"优点\":[],\"缺点\":[]} 3. **只返回json字符串，不要进行任何解释**"
                },
                {
                    "role": "user",
                    "content": query +'/no_think'
                }
            ],
            "stream": False  # 关键！必须设为 False，否则是流式输出
        }
        try:
            response = requests.post(self.ollama_url, json=payload, timeout=30)
            response.raise_for_status()
            # Ollama 返回的是 JSON，content 在 "message" -> "content"
            return response.json()["message"]["content"].split("</think>")[-1]
        except Exception as e:
            raise RuntimeError(f"Ollama API 调用失败: {e}")


    def _parse_analysis_result(self, response: dict) -> Tuple[List[str], List[str]]:
        """
        解析Ollama返回的分析结果

        :param response: API返回的原始JSON数据
        :return: (优点列表, 缺点列表)
        :raises: ValueError 当结果格式不符合预期时
        """
        try:
            # 检查响应是否包含必需的字段
            if not isinstance(response, dict):
                raise ValueError("API响应不是有效的JSON对象")

            # 获取优点和缺点列表
            advantages = response.get("优点", [])
            disadvantages = response.get("缺点", [])

            # 验证类型
            if not isinstance(advantages, list) or not isinstance(disadvantages, list):
                raise ValueError("优点或缺点字段不是列表类型")

            # 过滤空值和非字符串项
            advantages = [str(item).strip() for item in advantages if item and str(item).strip()]
            disadvantages = [str(item).strip() for item in disadvantages if item and str(item).strip()]

            return advantages, disadvantages

        except Exception as e:
            raise ValueError(f"结果解析失败: {str(e)}")


# 使用示例
if __name__ == '__main__':
    # 初始化分析器
    carid= 305
    analyzer = OllamaCommentAnalyzer(ollama_url='http://127.0.0.1:11434/api/chat', model_name='qwen3:30b-a3b')

    review_db = UserReviewDB()
    reviews = review_db.get_reviews_by_carid(carid)
    analyzer_db = CommentAnalysisDB()
    for review in reviews:
        try:
            commit = analyzer_db.get_analysis_by_commit_id(review['id'])
            if commit:
                print(f"{commit}已经分析过了，跳过...")
                continue
            review_content = review['review_content']
            single_result = analyzer.analyze_comment(review_content)
            print(f"优点: {single_result['advantages']}")
            print(f"缺点: {single_result['disadvantages']}")
            if len(single_result['advantages']) > 0 or len(single_result['disadvantages']) > 0:
                analysis_id = analyzer_db.insert_analysis(
                    review['id'],
                    ','.join(single_result['advantages']),
                    ','.join(single_result['disadvantages'])
                )
                print(f"评论分析结果保存成功，ID: {analysis_id}")
            else:
                print("无有效分析结果")
        except Exception as e:
            print(f"处理评论时发生错误：{e}")

    # 测试评论
    # test_comments = [
    #     "动力强劲，加速快，不过悬挂偏硬，过减速带不太舒服。",
    #     "内饰豪华，配置丰富，但车机系统偶尔会卡顿。"
    # ]

    # 单条评论分析

    # # 批量分析
    # print("\n批量分析结果:")
    # batch_results = analyzer.batch_analyze(test_comments)
    # for i, result in enumerate(batch_results, 1):
    #     print(f"\n评论{i}:")
    #     print(f"优点: {result['advantages']}")
    #     print(f"缺点: {result['disadvantages']}")
    #     if 'error' in result:
    #         print(f"错误: {result['error']}")



